//
//  UITextView-Extension.swift
//  表情键盘
//
//  Created by lujun on 2021/11/24.
//

import UIKit

extension UITextView {
    
    func getEmoticonString() -> String{
        let attrMStr = NSMutableAttributedString(attributedString: attributedText)
        let range = NSRange(location: 0, length: attrMStr.length)
        attrMStr.enumerateAttributes(in: range, options: []) { (dict, rang, _) -> Void in
            if let attachment =  dict[NSAttributedString.Key(rawValue: "NSAttachment")] as? EmoticonAttachment {
                attrMStr.replaceCharacters(in: rang, with: attachment.chs!)
            }
          }
        return attrMStr.string
        
    }
    
    func insertEmoticon(emoticon: Emoticon){
        if emoticon.isEmpty {
            return
        }
        if emoticon.isRemove {
            deleteBackward()
            return
        }
        //苹果的表情插入
        if emoticon.emojiCode != nil {
            //光标所在的位置
            let textRange = selectedTextRange!
            replace(textRange, withText: emoticon.emojiCode!)
            return
        }
        //普通表情
        //图文混排
        let attachment = EmoticonAttachment()
        attachment.chs = emoticon.chs
        attachment.image = UIImage(contentsOfFile: emoticon.pngPath!)
        let font = self.font!
        attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
        let attachmentImgStr = NSAttributedString(attachment: attachment)
       
        
        //保留原来的数据 可变字符串
        let attrMStr = NSMutableAttributedString(attributedString: attributedText)
       // debugPrint(attrMStr)
        let range = selectedRange
        
        attrMStr.replaceCharacters(in: range, with: attachmentImgStr)
        attributedText = attrMStr
        self.font = font
         //将光标设置原来位置 + 1
//        length 是选中的多少字符串
        selectedRange = NSRange(location: range.location + 1 , length: 0)
        
    }
}
